using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace OrderManagement.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class OrderController : ControllerBase
    {
        OrderService orderService = new OrderService();

        
        [HttpPost(Name = "AddOrder")]
        [Consumes("application/json")]
        public string addOrder([FromBody] JObject jsonObj)
        {
            var jsonStr = JsonConvert.SerializeObject(jsonObj);
            var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);

            string commodityName = jsonParams.commodityName;
            string customer = jsonParams.customer;
            double price = jsonParams.price;

            Order order = new Order();
            order.CommodityName = commodityName;
            order.Customer = customer;
            order.Price = price;

            orderService.add(order);
            return "add successful";
        }

        [HttpPost(Name = "DeleteOrder")]
        [Consumes("application/json")]
        public string deleteOrder([FromBody] JObject jsonObj)
        {
            var jsonStr = JsonConvert.SerializeObject(jsonObj);
            var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);

            int id = jsonParams.id;
            orderService.delete(id);

            return "delete successful";
        }



        [HttpPost(Name = "UpdateOrder")]
        [Consumes("application/json")]
        public string updateOrder([FromBody] JObject jsonObj)
        {
            var jsonStr = JsonConvert.SerializeObject(jsonObj);
            var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonStr);

            int id = jsonParams.id;
            string commodityName = jsonParams.commodityName;
            string customer = jsonParams.customer;
            double price = jsonParams.price;

            Order order = orderService.selectById(id);
            order.CommodityName = commodityName;
            order.Customer= customer;
            order.Price= price;

            orderService.update(order);
            return "update successful";
        }

        [HttpGet(Name = "GetOrder")]
        [Consumes("application/json")]
        public string getOrder(int id)
        {
            Order order = orderService.selectById(id);
            string jsonStr =  JsonConvert.SerializeObject(order);
            return jsonStr;
        }

    }
}